import { Component, OnChanges, OnDestroy, OnInit, SimpleChanges } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CommonService } from 'src/app/service/common/common.service';
import { FeeEnquiryService } from 'src/app/service/fee-enquiry/fee-enquiry.service';
import { PayService } from 'src/app/service/fee-enquiry/pay.service';
import { MessageService } from 'src/app/service/message.service';

@Component({
  selector: 'app-owe-fee',
  templateUrl: './owe-fee.component.html',
  styleUrls: ['./owe-fee.component.scss']
})
export class OweFeeComponent implements OnInit {

  usageCode = ''
  address = ''
  state: any = {
    un: { color: 'red', value: '未缴费'  },
    paying: { color: 'orange', value: '支付中' },
    done: { color: 'green', value: '已缴费' }
  }
  constructor(
    private feeEnquiry: FeeEnquiryService,
    private message: MessageService,
    private route: ActivatedRoute,
    private common: CommonService,
    private modal: NzModalService,
    private pay: PayService
  ) { }
  
  ngOnInit(): void {
    this.common.setRightInfoVisible(false)

    this.route.queryParams.subscribe((res: any) => {
      this.usageCode = res.usageCode
      this.address = res.address
      this.getFeeBill()
    })
  }

  cols = {
    'name': '户名',
    // 'quantity': '水量(m³)',
    'prepayAmt': '余额(元)',
    'falsify': '违约金(元)',
    'total': '费用合计(元)',
    // 'state': '缴费状态',
    '操作': '操作',
  }
  data = []
  dataLoading = false
  pageNumber = 1
  pageSize = 10
  total = 0
  getFeeBill(){
    this.dataLoading = true
    this.data = []
    this.feeEnquiry._getFeeBill(this.usageCode, this.pageNumber, this.pageSize, 'un').subscribe({
      next: res => {
        if(res && res.resultList){
          this.data = res.resultList.map((item: any) => {
            item.falsify = parseFloat(item.falsify)
            item.total = parseFloat(item.total)
            // item.total = 0
            item.prepayAmt = parseFloat(item.prepayAmt)

            return item
          })
          this.total = res.totalNumber
        }
        this.dataLoading = false
      },
      error: error => {
        this.message.error('查询数据错误, 请稍后再试')
        this.dataLoading = false
      }
    })
  }

  // private String usageCode;//用户编号
  // private String productName;
  // private String totalFee;//实际支付金额
  // private String owedFee;//账单欠费金额
  // private String frontCode;//支付来源，政务服务网（ZW）、微信公众号(WX)、穗好办（SHB）、网上营业厅(WT)、微信小程序(WXMINI)
  // private String month;//多个以逗号分割
  // private String code;//登录操作码，微信小程序支付需要

  //#region 缴费
  payModalVisible = false
  payData: any = null
  goPay(data: any){
    console.log(data)
    this.payData = data
    // 支持预付费
    if((parseFloat(this.payData.prepayAmt) >= parseFloat(this.payData.total)) && parseFloat(this.payData.total) > 0){
      this.modal.confirm({
        nzContent: '当前编号可直接使用余额抵扣，是否进行抵扣？',
        nzCancelText: '继续缴纳',
        nzOkText: '去抵扣',
        nzOnOk: () => {
          console.log('去抵扣')
          this.payByBalance()
        },
        nzOnCancel: () => {
          console.log('继续缴纳')
          this.payModalVisible = true
        }
      })

      return
    }
    this.payModalVisible = true
  }
  payModalClose(e: string){
    this.pageNumber = 1
    this.dataLoading = true
    this.data = []
    if(!e){ // 订单号bu存在
      this.getFeeBill()
      return
    }

    // 订单号存在 解锁订单
    this.feeEnquiry.cancelOrder(e).subscribe({
      next: (res: any) => {
        console.log(res)
        this.getFeeBill()
      },
      error: () => {
        this.message.info('账单解锁失败,请稍后刷新页面重试')
        this.getFeeBill()
      }
    })
  }

  // 预付费抵扣
  payByBalance(){
    let param = {
      usageCode: this.payData['code'],
      month: this.payData['month'],
      frontCode: 'WXMINI',
      prepayAmt: this.payData['prepayAmt'],//账户余额
      owedFee: this.payData['total'] //欠费金额
    }
    this.pay._payByBalance(param).subscribe({
      next: (res: any) => {
        if(res.result === 'success'){
          this.message.successModal('抵扣成功')
        }else{
          this.message.error('抵扣失败,请重试')
        }
        this.getFeeBill()
      },
      error: (err: any) => {
        this.message.error('抵扣失败,请重试')
        this.getFeeBill()
      }
    })
  }
  //#endregion

}
